package com.inet.Test06;


import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * @Author weijingchen
 * @Date 2025/6/26 20:38
 * @Version 1.0.0
 */
public class MyRunnable implements Runnable {
    Socket socket;

    public MyRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {

            UUID uuid = UUID.randomUUID();
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("src/main/resources/" + uuid.toString() + ".txt"));
            int len;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1) {
                System.out.println("len = " + len);
                bos.write(bytes, 0, len);
            }
            // 刷新缓冲区,写入文件
            bos.flush();
            // 回写数据
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}
